<?php

namespace app\load\service;

use app\load\loadModel\WorksModel;
use think\db\BaseQuery;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Model;
use think\Paginator;

/**
 * 工作汇报
 */
class WorkService
{
    /**
     * 列表
     * @throws DbException
     */
    public function list($where, $filed = '*', $limit = 10, $page = 1): Paginator
    {
        return WorksModel::Work()->list($where, $filed, $limit, $page);
    }

    /**
     * 详情
     * @param array $where
     * @param string $filed
     * @param $is_this
     * @return array|mixed|BaseQuery|Model|void|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info(array $where, string $filed, $is_this)
    {
        $data = WorksModel::Work()->info($where, $filed);
        if ($data) {
            if ($is_this == 1) {
                $wheres['from_uid'] = JWT_UID;
            } else {
                $wheres['to_uid'] = JWT_UID;
            }
            WorksModel::WorkRecord()->where('wid', $data['id'])->where($wheres)
                ->update(['read_time' => time()]);
        }
        return $data;
    }


    /**
     * 添加
     * @param $param
     * @param $user_id | 发送人
     * @return void
     * @throws \Exception
     */
    public function save($param, $user_id)
    {

        $workData = array_merge($param, [
            'admin_id' => $user_id,
            'create_time' => time(),
        ]);
        // 开启事务
        Db::startTrans();
        try {
            //添加
            if (empty($param['id'])) {
                $w_id = WorksModel::Work()->strict(false)->field(true)->insertGetId($workData);
                $users = explode(',', $param['type_user']);
                $send_data = [];
                foreach ($users as $value) {
                    if ($value && $value != $user_id) {
                        $send_data[] = [
                            'wid' => $w_id,
                            'to_uid' => $value,
                            'from_uid' => $user_id,
                            'send_time' => time(),
                        ];
                    }
                }
                WorksModel::WorkRecord()->strict(false)->field(true)->insertAll($send_data);
            } else {//修改
                $w_id = WorksModel::Work()->strict(false)->field(true)->update($workData);
            }

            Db::commit();
            $param['uid'] = $user_id;
            api_add_log('send', $w_id, $param);
        } catch (\Exception $e) {
            Db::rollback();
            throw  $e;
        }
    }
}